import { flows } from "./flows";
import { actions } from "./actions";
import { SEP } from "../helpers/constents";

function warning() {
  throw new Error(
    'You are calling "dispatch" or "getState" without applying RuaMiddleware! ' +
      "Please create your store with RuaMiddleware first!"
  );
}

export let dispatch = warning;
export let getState = warning;

export default () => store => {
  dispatch = store.dispatch;
  getState = store.getState;

  return next => action => {
    const { isFlow } = action;
    let result;

    if (isFlow) {
      const { type, payload } = action;
      const [namespace, realType] = type.split(SEP);

      result = flows[namespace][realType](actions, payload, getState);
    } else {
      result = next(action);
    }

    return result;
  };
};
